package view;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Vector;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import dao.BookDao;
import dao.BookTypeDao;
import model.BookType;
import util.DbUtil;
import util.StringUtil;
public class BookTypeManageInterFrm extends JInternalFrame {
    private JTextField s_bookTypeNameTxt;
    private JTable bookTypeTable;
    private JTextArea bookTypeDescTxt = new JTextArea();
    private DbUtil dbUtil = new DbUtil();
    private BookTypeDao bookTypeDao = new BookTypeDao();
    private BookDao bookDao = new BookDao();
    private JTextField idTxt;
    private JTextField bookTypeNameTxt;
    private BookType bookType;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    BookTypeManageInterFrm frame = new BookTypeManageInterFrm();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public BookTypeManageInterFrm() {
        setClosable(true);
        setIconifiable(true);
        setTitle("\u56FE\u4E66\u7C7B\u522B\u7BA1\u7406");
        setBounds(100, 100, 582, 567);

        JLabel lblNewLabel = new JLabel("\u56FE\u4E66\u7C7B\u522B\u540D\u79F0\uFF1A");

        s_bookTypeNameTxt = new JTextField();
        s_bookTypeNameTxt.setColumns(10);

        JButton btnNewButton = new JButton("\u67E5\u8BE2");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bookTypeSearchActionPerformed(e);
            }


        });
        btnNewButton.setIcon(new ImageIcon(BookTypeManageInterFrm.class.getResource("/images/search.png")));

        JScrollPane scrollPane = new JScrollPane();


        JPanel panel = new JPanel();
        panel.setBorder(new TitledBorder(null, "\u8868\u5355\u64CD\u4F5C", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        panel.setToolTipText("");

        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
                groupLayout.createParallelGroup(Alignment.TRAILING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addContainerGap(85, Short.MAX_VALUE)
                                .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
                                        .addGroup(groupLayout.createSequentialGroup()
                                                .addComponent(lblNewLabel)
                                                .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(s_bookTypeNameTxt, GroupLayout.PREFERRED_SIZE, 139, GroupLayout.PREFERRED_SIZE)
                                                .addGap(61)
                                                .addComponent(btnNewButton))
                                        .addComponent(scrollPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                                        .addComponent(panel, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 411, GroupLayout.PREFERRED_SIZE))
                                .addGap(70))
        );
        groupLayout.setVerticalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addGap(38)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(btnNewButton)
                                        .addComponent(s_bookTypeNameTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblNewLabel))
                                .addGap(35)
                                .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 163, GroupLayout.PREFERRED_SIZE)
                                .addGap(34)
                                .addComponent(panel, GroupLayout.PREFERRED_SIZE, 216, GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(27, Short.MAX_VALUE))
        );

        JLabel lblNewLabel_1 = new JLabel("\u7F16\u53F7\uFF1A");

        idTxt = new JTextField();
        idTxt.setEditable(false);
        idTxt.setColumns(10);

        JLabel lblNewLabel_2 = new JLabel("\u56FE\u4E66\u7C7B\u522B\u540D\u79F0\uFF1A");

        bookTypeNameTxt = new JTextField();
        bookTypeNameTxt.setColumns(10);

        JLabel lblNewLabel_3 = new JLabel("\u63CF\u8FF0\uFF1A");



        JButton btnNewButton_1 = new JButton("\u4FEE\u6539");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bookTypeUpdateActionPerformed(e);
            }
        });
        btnNewButton_1.setIcon(new ImageIcon(BookTypeManageInterFrm.class.getResource("/images/modify.png")));

        JButton btnNewButton_2 = new JButton("\u5220\u9664");
        btnNewButton_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bookTypeDeleteActionPerformed(e);
            }
        });
        btnNewButton_2.setIcon(new ImageIcon(BookTypeManageInterFrm.class.getResource("/images/delete.png")));
        GroupLayout gl_panel = new GroupLayout(panel);
        gl_panel.setHorizontalGroup(
                gl_panel.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel.createSequentialGroup()
                                .addGap(22)
                                .addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
                                        .addGroup(gl_panel.createSequentialGroup()
                                                .addComponent(btnNewButton_1)
                                                .addGap(61)
                                                .addComponent(btnNewButton_2))
                                        .addGroup(gl_panel.createSequentialGroup()
                                                .addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
                                                        .addComponent(lblNewLabel_3)
                                                        .addComponent(lblNewLabel_1))
                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                .addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
                                                        .addGroup(gl_panel.createSequentialGroup()
                                                                .addComponent(idTxt, GroupLayout.PREFERRED_SIZE, 66, GroupLayout.PREFERRED_SIZE)
                                                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                                                .addComponent(lblNewLabel_2)
                                                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                                                .addComponent(bookTypeNameTxt, GroupLayout.PREFERRED_SIZE, 114, GroupLayout.PREFERRED_SIZE))
                                                        .addComponent(bookTypeDescTxt, GroupLayout.PREFERRED_SIZE, 307, GroupLayout.PREFERRED_SIZE))))
                                .addContainerGap(30, Short.MAX_VALUE))
        );
        gl_panel.setVerticalGroup(
                gl_panel.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(lblNewLabel_1)
                                        .addComponent(idTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblNewLabel_2)
                                        .addComponent(bookTypeNameTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                .addGap(18)
                                .addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
                                        .addComponent(lblNewLabel_3)
                                        .addComponent(bookTypeDescTxt, GroupLayout.PREFERRED_SIZE, 82, GroupLayout.PREFERRED_SIZE))
                                .addGap(18)
                                .addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
                                        .addComponent(btnNewButton_1)
                                        .addComponent(btnNewButton_2))
                                .addContainerGap(18, Short.MAX_VALUE))
        );
        panel.setLayout(gl_panel);

        bookTypeTable = new JTable();
        bookTypeTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                bookTypeTableMousePressed(e);
            }
        });
        bookTypeTable.setModel(new DefaultTableModel(
                new Object[][] {
                },
                new String[] {"\u7F16\u53F7", "\u56FE\u4E66\u7C7B\u522B\u540D\u79F0", "\u56FE\u4E66\u7C7B\u522B\u63CF\u8FF0"}
        ) {
            boolean[] columnEditables = new boolean[] {false, false, false};
            public boolean isCellEditable(int row, int column) {
                return columnEditables[column];
            }
        });
        bookTypeTable.getColumnModel().getColumn(1).setPreferredWidth(146);
        bookTypeTable.getColumnModel().getColumn(2).setPreferredWidth(128);
        scrollPane.setViewportView(bookTypeTable);
        getContentPane().setLayout(groupLayout);
        bookTypeDescTxt.setBorder(new LineBorder(new java.awt.Color(127,157,185), 1, false));
        this.fillTable(new BookType());
    }

    /**
     * 初始化表格
     * @param bookType
     */
    private void fillTable(BookType bookType) {
        DefaultTableModel dtm = (DefaultTableModel) bookTypeTable.getModel();
        dtm.setRowCount(0);
        Connection con = null;
        try {
            con = dbUtil.getCon();
            ResultSet rs = bookTypeDao.list(con, bookType);
            while (rs.next()) {
                Vector v = new Vector();
                v.add(rs.getString("id"));
                v.add(rs.getString("bookTypeName"));
                v.add(rs.getString("bookTypeDesc"));
                dtm.addRow(v);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 图书类别修改
     * @param evt
     */
    private void bookTypeUpdateActionPerformed(ActionEvent evt){
        String id = idTxt.getText();
        String bookTypeName=bookTypeNameTxt.getText();
        String bookTypeDesc=bookTypeDescTxt.getText();
        if (StringUtil.isEmpty(id)) {
            JOptionPane.showMessageDialog(null, "请选择要修改的记录");
            return;
        }
        BookType bookType=new BookType(Integer.parseInt(id),bookTypeName,bookTypeDesc);
        Connection con = null;
        try {
            con = dbUtil.getCon();
            int modifyNum = bookTypeDao.update(con, bookType);
            if (modifyNum == 1) {
                JOptionPane.showMessageDialog(null,"修改成功");
                this.resetValue();
                this.fillTable(new BookType());
            } else {
                JOptionPane.showMessageDialog(null,"修改失败");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            JOptionPane.showMessageDialog(null,"修改失败");
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 图书类别删除
     * @param evt
     */
    private void bookTypeDeleteActionPerformed(ActionEvent evt){
        String id = idTxt.getText();
        if (StringUtil.isEmpty(id)) {
            JOptionPane.showMessageDialog(null, "请选择要删除的数据");
            return;
        }
        int n = JOptionPane.showConfirmDialog(null, "确定删除吗？");
        if (n == 0) {
            Connection con = null;
            try {
                con = dbUtil.getCon();
                boolean flag=bookDao.existBookByTypeId(con, id);
                if(flag){
                    JOptionPane.showMessageDialog(null, "该图书类型下有图书");
                    int a=JOptionPane.showConfirmDialog(null,"是否将该图书类型设为不可用");
                    if(a==0){
                        bookType.setAvailable(false);
                    }
                    return;
                }
                int deleteNum = bookTypeDao.delete(con, id);
                if (deleteNum == 1) {
                    JOptionPane.showMessageDialog(null, "删除成功");
                    resetValue();
                    fillTable(new BookType());
                } else {
                    JOptionPane.showMessageDialog(null, "删除失败");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    dbUtil.closeCon(con);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 表格行点击处理
     * @param evt
     */
    private void bookTypeTableMousePressed(MouseEvent evt){
        //
        int row = bookTypeTable.getSelectedRow();
        idTxt.setText((String) bookTypeTable.getValueAt(row, 0));
        bookTypeNameTxt.setText((String) bookTypeTable.getValueAt(row, 1));
        bookTypeDescTxt.setText((String) bookTypeTable.getValueAt(row, 2));
    }

    /**
     * 图书类别搜索
     * @param e
     */
    private void bookTypeSearchActionPerformed(ActionEvent e) {
        String s_bookTypeName = this.s_bookTypeNameTxt.getText();
        BookType bookType = new BookType();
        bookType.setBookTypeName(s_bookTypeName);
        this.fillTable(bookType);
    }

    /**
     * 重置表单
     */
    private void resetValue() {
        this.idTxt.setText("");
        this.bookTypeNameTxt.setText("");
        this.bookTypeDescTxt.setText("");
    }
}
